package com.abing.permissionsys.security.service;

import com.abing.permissionsys.entity.vo.SysUserVO;
import com.abing.permissionsys.exception.BadRequestException;
import com.abing.permissionsys.security.security.JwtUser;
import com.abing.permissionsys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username){
        SysUserVO userVO=new SysUserVO();
        userVO.setUsername(username);
        // 查询用户信息
        SysUserVO sysUserVO = userService.selectOne(userVO);
        if (sysUserVO == null) {
            throw new BadRequestException("账号不存在");
        } else {
            return createJwtUser(sysUserVO);
        }
    }

    public UserDetails createJwtUser(SysUserVO user) {
        return new JwtUser(
                user.getUserId(),
                user.getUsername(),
                user.getPassword(),
               permissionService.mapToGrantedAuthorities(user),
                true,
                user.getGmtCreate(),
                user.getGmtModified()
        );
    }
}
